import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import {
  Input,
  Button,
  Select,
  Radio,
  Message,
  Upload,
  Icon
} from '@alifd/next';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
import { withRouter } from 'react-router-dom';
import axios from 'axios';
import { saveImageToIpfs, ipfsPrefix } from '../../../config';

const { Option } = Select;
const { Group: RadioGroup } = Radio;


class NewPostForm extends Component {
  static displayName = 'NewPostForm';
  static propTypes = {};
  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      value: {
        status: 'pending',
        cover: []
      },
      workImages: [],
      unauthorized: true
    };
  }

  formChange = (value) => {
    this.setState({
      value,
    });
  };

  validateAllFormField = () => {
    this.refs.form.validateAll((errors, values) => {
      if (errors) {
        console.log({ errors });
      }
      console.log("values: ", values);
      // 把workImages从数组转成以","号拼接的字符串
      // 获取workId（this.state.value.workId[0].response.data.id）
      // 把所有数据组成JSON格式用axios.post方法传往后台
      let workImages = this.state.workImages.join(",");
      let workId = this.state.value.workId[0].response.data.id;
      let workName = this.state.value.workName;
      let workDesc = this.state.value.workDesc;
      let authorId = localStorage.getItem("id");
      let workType = this.state.value.workType.join(",");
      let price = this.state.unauthorized ? 0 : this.state.value.price;
      let authorized = this.state.unauthorized ? 0 : 1;
      axios.post("http://localhost:9080/work/add", {
        workId: workId,
        workName: workName,
        workDesc: workDesc,
        authorId: authorId,
        workImages: workImages,
        workType: workType,
        authPrice: price,
        authorized: authorized
      }).then((res) => {
        Message.success('提交成功');
      }).catch((err) => {
        console.log(err);
        Message.warning('提交失败，请联系管理员或稍后重试！');
      });
    });
  };

  handleImageUpload = async(file) => {
    let hash = await saveImageToIpfs(file);
    console.log(hash);
    hash = ipfsPrefix + hash;
    console.log(hash);
    let joined = this.state.workImages.concat(hash);
    console.log(joined);
    this.setState({
      workImages: joined
    });
    return false;
  }

  beforeFileUpload = (info) => {
    console.log('beforeUpload callback : ', info);
  }

  onFileChange = (info) => {
    console.log('onChange callback : ', info);
  }

  authorizedChange = (value) => {
    console.log("value: ", value);
    if(value === "authorized" ) {
      this.setState({
        unauthorized: false
      });
    }else {
      this.setState({
        unauthorized: true
      });
    }
  }

  render() {
    return (
      <IceContainer style={styles.container}>
        <div style={styles.title}>版权认证</div>
        <IceFormBinderWrapper
          value={this.state.value}
          onChange={this.formChange}
          ref="form"
        >
          <div style={styles.formContent}>
            <div style={styles.formItem}>
              <div style={styles.formLabel}>作品名称</div>
              <IceFormBinder
                required
                triggerType="onBlur"
                message="作品名称不能为空"
                name="workName"
              >
                <Input
                  placeholder="请输入作品名称"
                  size="large"
                  style={{ width: '400px' }}
                />
              </IceFormBinder>
              <div style={styles.formError}>
                <IceFormError name="workName" />
              </div>
            </div>
            <div style={styles.formItem}>
              <div style={styles.formLabel}>作品简介</div>
              <IceFormBinder
                required
                triggerType="onBlur"
                message="作品简介不能为空"
                name="workDesc"
              >
                <Input.TextArea
                  placeholder="请输入作品简介"
                  size="large"
                  style={{ width: '400px' }}
                />
              </IceFormBinder>
              <div style={styles.formError}>
                <IceFormError name="workDesc" />
              </div>
            </div>
            <div style={styles.formItem}>
              <div style={styles.formLabel}>作品类别</div>
              <IceFormBinder name="workType">
                <Select
                  placeholder="请选择"
                  mode="multiple"
                  size="large"
                  style={{ width: '400px' }}
                >
                  <Option value="汽车">汽车</Option>
                  <Option value="金融">金融</Option>
                  <Option value="其他">其他</Option>
                </Select>
              </IceFormBinder>
            </div>
            <div style={styles.formItem}>
              <div style={styles.formLabel}>封面图</div>
              <div style={{ height: "100px"}}>
                {
                  this.state.workImages.map((item, index) => {
                    return(
                        <img key={index} style={{ height: "100px", width: "100px" }} src={item} alt="" /> 
                    );
                  })
                }
              </div>
              <IceFormBinder name="workImages">
                <Upload
                  shape="card"
                  style={{display: 'inline-block'}}
                  beforeUpload={this.handleImageUpload}
                >
                  上传图片
                </Upload>
              </IceFormBinder>
            </div>
            <div style={styles.formItem}>
              <div style={styles.formLabel}>文件</div>
              <IceFormBinder name="workId">
                <Upload 
                  listType="text"
                  action="http://localhost:9080/files/upload"
                  accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp, .doc, .txt, .pdf"
                  beforeUpload={this.beforeFileUpload}
                  onChange={this.onFileChange}
                >
                  <Button type="primary" style={{margin: '0 0 10px'}}>上传作品附件</Button>
                </Upload>
              </IceFormBinder>
            </div>
            <div style={styles.formItem}>
              <div style={styles.formLabel}>是否可授权</div>
              <IceFormBinder name="status">
                <RadioGroup
                  onChange={this.authorizedChange}
                  dataSource={[
                    {
                      value: 'authorized',
                      label: '可授权',
                    },
                    {
                      value: 'unauthorized',
                      label: '不可授权',
                    },
                  ]}
                />
              </IceFormBinder>
            </div>
            <p style={styles.tips}>
              提醒：选择“授权”状态，才可以进行作品授权交易
            </p>
            <div style={styles.formItem}>
              <div style={styles.formLabel}>价格</div>
              <IceFormBinder name="price">
                <Input
                  placeholder="请输入价格"
                  size="large"
                  disabled={this.state.unauthorized}
                  style={{ width: '400px' }}
                />
              </IceFormBinder>
            </div>
            <Button
              type="primary"
              size="large"
              style={styles.submitButton}
              onClick={this.validateAllFormField}
            >
              提 交
            </Button>
          </div>
        </IceFormBinderWrapper>
      </IceContainer>
    );
  }
}

const styles = {
  title: {
    marginBottom: '30px',
    fontSize: '18px',
    fontWeight: '500',
    color: 'rgba(0, 0, 0,.85)',
  },
  formContent: {
    marginLeft: '30px',
  },
  formItem: {
    marginBottom: '25px',
    display: 'flex',
    alignItems: 'center',
  },
  formLabel: {
    width: '70px',
    marginRight: '15px',
    textAlign: 'right',
  },
  formError: {
    marginLeft: '10px',
  },
  tips: {
    color: '#f37327',
    fontSize: '12px',
    margin: '20px 0',
  },
  submitButton: {
    marginLeft: '85px',
  },
};

export default withRouter(NewPostForm);